//
//  NGbbsTableView.swift
//  NingguoForum
//
//  Created by zhengsw on 2025/7/17.
//  Copyright © 2025 zhengsw. All rights reserved.
//

import UIKit
import ESPullToRefresh

// 在 NGbbsTableView.swift 中定义协议
protocol NGbbsTableViewDelegate: AnyObject {
    func didSelectCollectionViewItem(section: Int, item: Int, itemModel: Any)
}

class NGbbsTableView: UIView {

    var tableView: UITableView!
    var datas: NSMutableArray!
    // 添加代理属性
    weak var delegate: NGbbsTableViewDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        datas = NSMutableArray()
        
        tableView = UITableView(frame: bounds, style: .grouped)
        tableView.backgroundColor = UIColor.clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(NGbbsTableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        // 关键：启用用户交互
        tableView.isUserInteractionEnabled = true
        
        // iOS 15+ 设置 section 间距
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        //提供下拉
        //修改 下拉 上拉刷新 文字提示
        var header: ESRefreshHeaderAnimator {
            get {
                let h = ESRefreshHeaderAnimator.init(frame: CGRect.zero)
                h.pullToRefreshDescription = "下拉刷新"
                h.releaseToRefreshDescription = "松开获取最新数据"
                h.loadingDescription = "下拉刷新..."
                return h
            }
        }
        self.tableView.es.addPullToRefresh(animator: header) { [weak self] in
            guard let self = self else { return }
            self.requestDatas()
        }
        self.addSubview(tableView)
        tableView.reloadData()
        requestDatas()
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    func requestDatas() {
        //获取数据
        HttpManager.sharedInstance.getCircleClass { [weak self] (successd:Array<ResponseCircleClassModel>) in
            guard let self = self else { return }
            self.tableView.es.stopPullToRefresh()
            let firstModel  = successd[0]
            print(firstModel.circle_list as Any)
            self.datas = NSMutableArray(array: successd)
            self.tableView.reloadData()
        } fail: { (fail) in
            
        }

    }
}

// MARK: - UITableViewDataSource
extension NGbbsTableView : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NGbbsTableViewCell
        let model = datas[indexPath.section] as! ResponseCircleClassModel
        cell.setModel(model: model)
        // 设置 CollectionView 点击回调
        cell.onCollectionViewItemTapped = { [weak self] collectionIndexPath in
            print("TableView section \(indexPath.section) 的 CollectionView item \(collectionIndexPath.row) 被点击")
            
            // 获取对应的数据
            if let model = self?.datas[indexPath.section] as? ResponseCircleClassModel,
               let itemModel = model.circle_list?[collectionIndexPath.row] {
                print("点击的项目: \(itemModel)")
                
                // 调用代理方法，将事件传递给外层 VC
                self?.delegate?.didSelectCollectionViewItem(section: indexPath.section,
                                                          item: collectionIndexPath.row,
                                                          itemModel: itemModel)
            }
        }
        return cell
    }
}

// MARK: - UITableViewDelegate
extension NGbbsTableView : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = datas[indexPath.section] as! ResponseCircleClassModel
        let height = ceil(Double(model.circle_list!.count)/2.0)*60 + 20
        return height
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("TableView cell 被点击: \(indexPath)")
        // 在这里处理 TableView cell 的点击事件
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let model = datas[section] as! ResponseCircleClassModel
        
        let view = UIView()
        view.backgroundColor = UIColor.clear
        
        let titleLabel = UILabel(frame: CGRectZero);
        titleLabel.backgroundColor = UIColor.clear
        titleLabel.text = model.name
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.bottom.equalTo(view)
        }
        return view
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        30
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        0.01
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
